# Author: Damian 'Rush' Kaczmarek
# License: MIT
# TODO Support super scripts

package Google;
use base Module;
use strict;
use utf8;
use LWP::UserAgent;
use HTML::Entities;

my $ua = LWP::UserAgent->new;
$ua->timeout(10);
$ua->env_proxy;
$ua->agent('Mozilla/5.0');

my $language = Config::get('language', 'en');
my $lastg;

sub parse_content
{
	if ($_[0] =~ /src=\/images\/calc_img\.gif/) {    # Calculator answer
			print "DUPA!\n";
		$_[0] =~ /<div id=res .*?>.*?<b>(.*?)<\/b>/;
		my $answer = $1;
		$answer =~ s/<(\/|)font[^>]*>//g;
		$answer =~ s/<sup>/^/g;
		$answer =~ s/<\/sup>//g;
		$answer = decode_entities($answer);
		return $answer;
	}

	# Little regexp magic now, hehe :-) I'm feeling lucky
	elsif ($_[0] =~ /<a href="([^"]*)" class=l.*?>(.*?)<\/a>/) {    # Search result"
		(my $url, my $title) = ($1, $2);
		$title =~ s/<em>(.*?)<\/em>/@{[Util::bold($1)]}/g;        # Replace bold characters with
		decode_entities($title);

		return $title . " - " . $url;
	}
}

sub get_google
{
	my $query = $_[0];
	$query =~ s/\+/%2B/g;
	my $response = $ua->get('http://google.com/search?hl=' . $language . '&q=' . $query);    # Do a query
	if ($response->is_success) {
		return parse_content($response->content);
	}
}

sub on_public
{
	my $time = time();
	my $text = $_[1];

	if ($text =~ /^!g (.*)/ && $time - $lastg > 5) {
		Core::send_msg(get_google($1));
		$lastg = $time;
	}
}
1;
